package com.cn.sys.main.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cn.sys.frame.util.page.PageData;
import com.cn.sys.frame.util.query.QueryBean;
import com.cn.sys.frame.util.query.QueryCondition;
import com.cn.sys.frame.web.BaseController;
import com.cn.sys.main.entity.SysRole;
import com.cn.sys.main.entity.SysUser;
import com.cn.sys.main.service.SysRoleService;

@Controller
@RequestMapping("sys/role")
public class SysRoleController extends BaseController {

	//private static final Logger logger = LoggerFactory.getLogger(SysRoleController.class);
	
	@Autowired
	private SysRoleService sysRoleService;
	
	@RequestMapping(value = "/toList.do", method = RequestMethod.GET)
	public String toList(HttpServletRequest request, Model model){
		return "sys/role/roleList";
	}
	
	@RequestMapping(value = "/toAdd.do", method = RequestMethod.GET)
	public String toAdd(String id, Model model) throws Exception{
		if(StringUtils.isNotBlank(id)&&StringUtils.isNumeric(id)){
			SysRole role = sysRoleService.get(Long.valueOf(id));
			model.addAttribute("role", role);
		}
		return "sys/role/roleAdd";
	}
	
	@RequestMapping(value = "/toView.do", method = RequestMethod.GET)
	public String toView(String id, Model model) throws Exception{
		if(StringUtils.isNotBlank(id)&&StringUtils.isNumeric(id)){
			SysRole role = sysRoleService.get(Long.valueOf(id));
			model.addAttribute("role", role);
		}
		return "sys/role/roleView";
	}
	
	@RequestMapping(value = "/list.do", method = RequestMethod.POST)
	@ResponseBody
	public Object list(HttpServletRequest request, String roleName) throws Exception{
		PageData<SysRole> pageData = createPageDataFromRequest(request);
		QueryCondition queryCondition = null;
		if(StringUtils.isNotBlank(roleName)){
			QueryBean qb = new QueryBean(" AND ROLE_NAME LIKE ?", "ROLE_NAME", "%"+roleName+"%");
			List<QueryBean> queryBeans = new ArrayList<QueryBean>();
			queryBeans.add(qb);
			queryCondition = new QueryCondition();
			queryCondition.setQueryBeanList(queryBeans);
		}
		sysRoleService.getPageData(pageData, queryCondition);
		return pageData.getPageDataMap();
	}
	
	@RequestMapping(value = "/validateRoleName.do", method = RequestMethod.POST)
	@ResponseBody
	public Object validateRoleName(String id, String name) throws Exception{
		QueryCondition queryCondition = new QueryCondition();
		if(StringUtils.isNotBlank(id)){
			QueryBean qb = new QueryBean(" AND ID <> ?", "ID", Long.valueOf(id));
			queryCondition.setQueryBean(qb);
		}
		long count = 0;
		if(StringUtils.isNotBlank(name)){
			queryCondition.setQueryBean(new QueryBean(" AND ROLE_NAME = ?", "ROLE_NAME", name));
			count = sysRoleService.getCount(queryCondition);
		}else {
			return false;
		}
		if(count>0){
			return false;
		}
		return true;
	}
	
	@RequestMapping(value = "/save.do", method = RequestMethod.POST)
	@ResponseBody
	public Object save(HttpServletRequest request, SysRole role) throws Exception{
		if(role !=null && role.getId() !=null){
			SysRole oldRole = sysRoleService.get(role.getId());
			role.setCreateTime(oldRole.getCreateTime());
			role.setCreateUser(oldRole.getCreateUser());
			role.setUpdateTime(new Date());
			role = sysRoleService.update(role);
		}else {
			role.setCreateTime(new Date());
			SysUser currentUser = getSessionUser(request);
			role.setCreateUser(currentUser!=null?currentUser.getUserName():null);
			role = sysRoleService.save(role);
		}
		Map<String, Object> result = new HashMap<String, Object>(1);
		if(role==null){
			result.put("success", false);
		}else {
			result.put("success", true);
		}
		return result;
	}
	
	@RequestMapping(value = "/delete.do", method = RequestMethod.POST)
	@ResponseBody
	public Object delete(HttpServletRequest request, String ids) throws Exception{
		Map<String, Object> result = new HashMap<String, Object>(2);
		if(ids!=null){
			int count = 0;
			String[] strArr = StringUtils.split(ids, ",");
			for (int i=0,len=strArr.length; i<len; i++) {
				String id = strArr[i];
				if(StringUtils.isNotBlank(id)&&StringUtils.isNumeric(id)){
					int resultCnt = sysRoleService.delete(Long.valueOf(id));
					if(resultCnt == 1){
						count ++;
					}
				}
			}
			if(count == strArr.length){
				result.put("success", true);
			} else {
				result.put("success", false);
				result.put("msg", (strArr.length - count)+"条记录删除失败!");
			}
			
		}else {
			result.put("success", false);
		}
		return result;
	}
	
	@RequestMapping(value = "/toAccredit.do", method = RequestMethod.GET)
	public String toAccredit(String id, Model model) throws Exception{
		model.addAttribute("roleId", id);
		model.addAttribute("moduleFunJson", sysRoleService.getModuleAndFunByRoleId(id));
		return "sys/role/roleAccredit";
	}
	
	@RequestMapping(value = "/saveRolePrivileges.do", method = RequestMethod.POST)
	@ResponseBody
	public Object saveRolePrivileges(String roleId, String moduleIds, String funcIds) throws Exception{
		Map<String, Object> result = new HashMap<String, Object>(1);
		if(StringUtils.isNotBlank(roleId)){
			Long roleIdL = Long.valueOf(roleId);
			boolean succes = sysRoleService.saveRoleModuleFun(roleIdL, moduleIds, funcIds);
			result.put("success", succes);
			if(!succes){
				result.put("msg", "授权角色失败");
			}
		}else {
			result.put("success", false);
		}
		return result;
	}
}
